#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;

#define Conv(addr) ((struct sockaddr *)&addr);

class InetAddr
{
private:
    void Host_to_Net()
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = inet_addr(_ip.c_str());
    }

    void Net_to_Host()
    {
        _ip = inet_ntoa(_addr.sin_addr);
        _port = ntohs(_addr.sin_port);
    }

public:
    InetAddr(uint16_t port, string ip = "0.0.0.0")
        : _ip(ip),
          _port(port)
    {
        Host_to_Net();
    }

    InetAddr(struct sockaddr_in &addr)
        : _addr(addr)
    {
        Net_to_Host();
    }

    string Ip(){return _ip;}
    uint16_t Port(){return _port;}
    struct sockaddr* Addr(){return Conv(_addr);}

    string Tostring()
    {
        return _ip + "-" + to_string(_port);
    }

    bool operator==(const InetAddr& addr)
    {
        return (addr._ip== _ip) && addr._port == _port;
    }

    socklen_t Length()
    {
        return sizeof(_addr);
    }

    ~InetAddr()
    {
    }

private:
    string _ip;
    uint16_t _port;
    struct sockaddr_in _addr;
};